from model.model import AlertConfigure
from common.analyzer_common.alert import AlertMap
from package.fastapi.job import scheduler_job


class AlertView(AlertConfigure):
    Prefix = 'analyzer:alert:cron:'

    @classmethod
    def execute(cls, id, name, category, supress, search, configure):
        """采集"""
        cls_ = AlertMap.get(category)
        if not cls_:
            raise Exception('该告警方式暂不支持')
        return cls_.check(id=id, category=category, name=name, supress=supress, search=search, configure=configure)

    @classmethod
    def create_alert(cls, session, body):
        item = cls.create_item(session=session, body=body, commit=False)

        scheduler_job.add_job(job_id=f'{cls.Prefix}{item.id}',
                              func=cls.execute, 
                              kwargs={'id':item.id, 'category': item.category, 'supress': item.supress, 'search': item.search, 'configure': item.configure}, 
                              cron=item.cron)
        session.commit()
        return item
    
    @classmethod
    def update_alert(cls, session, filter_, update):
        item = cls.update_item(session=session, filter_=filter_, update=update, commit=False)

        scheduler_job.add_job(job_id=f'{cls.Prefix}{item.id}',
                              func=cls.execute, 
                              kwargs={'id':item.id, 'category': item.category, 'supress': item.supress, 'search': item.search, 'configure': item.configure}, 
                              cron=item.cron)
        
        session.commit()
        return item

    @classmethod
    def delete_alert(cls, session, filter_):
        items = cls.get_items(session=session, filter_=filter_)
        for item in items:
            scheduler_job.delete_job(job_id=f'{cls.Prefix}{item.id}')
        return cls.delete_items(session, filter_)
